package com.youyiwen.Service.impl;

import com.youyiwen.Bean.Question;
import com.youyiwen.Bean.User;
import com.youyiwen.Mapper.QuestionMapper;
import com.youyiwen.Mapper.UserMapper;
import com.youyiwen.Service.QuestionService;
import com.youyiwen.Service.ReplyService;
import com.youyiwen.dto.PageInitDTO;
import com.youyiwen.dto.QuestionDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhaoyang
 * @Date: 2021/03/19
 */
@Service
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ReplyService replyService;

    @Override
    public PageInitDTO questionList(Integer page, Integer size) {

        PageInitDTO pageInitDTO = new PageInitDTO();
        Integer totolCount = questionMapper.count();
        pageInitDTO.setPageInition(totolCount, page , size);

        if (page<1){
            page = 1;
        }
        if(page > pageInitDTO.getTotalPage()){
            page = pageInitDTO.getTotalPage();
        }

        Integer offSet = size * ( page - 1 );


        List<Question> questions = questionMapper.selectQuestions(offSet,size);

        //返回一个questionDTOlist
        List<QuestionDTO> questionDTOList = new ArrayList<>();
        for (Question q : questions) {
            User user = userMapper.selectUserByName(q.getUserName());
            QuestionDTO questionDTO = new QuestionDTO();
            BeanUtils.copyProperties(q, questionDTO);
            questionDTO.setUser(user);

            questionDTOList.add(questionDTO);
        }
        pageInitDTO.setQuestions(questionDTOList);

        return pageInitDTO;
    }

    @Override
    public QuestionDTO getById(String id) {
        Question question = questionMapper.getById(id);
        User user = userMapper.selectUserByName(question.getUserName());
        QuestionDTO questionDTO = new QuestionDTO();
        BeanUtils.copyProperties(question,questionDTO);
        questionDTO.setUser(user);
        return questionDTO;
    }

    @Override
    public void incView(String id) {
        questionMapper.updateViewCount(id);
    }
}
